package me.chan.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by JanGin on 2017/6/16.
 */
public class ReflectUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ReflectUtil.class);

    public static Object newInstance(Class<?> clazz) {
        Object instantce;
        try {
            instantce = clazz.newInstance();
        } catch (InstantiationException e) {
            //e.printStackTrace();
            LOGGER.error("could not instance the given class", e);
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            LOGGER.error("could not instance the given class", e);
            throw new RuntimeException(e);
        }
        return instantce;
    }


    public static Object invokeMethod(Object obj, Method method, Object... params) {
        Object result = null;
         try {
             method.setAccessible(true);
             result = method.invoke(obj, params);
         } catch (InvocationTargetException e) {
            LOGGER.error("could not invoke the method", e);
             throw new RuntimeException(e);
         } catch (IllegalAccessException e) {
             e.printStackTrace();
         }
        return result;
    }

    public static void setField(Object obj, Field field, Object value) {
        field.setAccessible(true);
        try {
            field.set(obj, value);
        } catch (IllegalAccessException e) {
            LOGGER.error("could not set the field value to the object", e);
            throw new RuntimeException(e);
        }
    }
}
